import R from "@/common/type/response";
import { NextApiResponse } from "next";
import { SysMenuService } from "@/common/service/sys_menu";
import { AuthenticatedRequest, withAuth } from "@/common/middleware/auth";

function buildTree(list: any[]) {
  const map: Record<number, any> = {};
  const roots: any[] = [];
  list.forEach(item => {
    map[item.menu_id] = { ...item, children: [] };
  });
  list.forEach(item => {
    if (item.parent_id && map[item.parent_id]) {
      map[item.parent_id].children.push(map[item.menu_id]);
    } else {
      roots.push(map[item.menu_id]);
    }
  });
  return roots;
}

export async function handler(req: AuthenticatedRequest, res: NextApiResponse) {
  try {
    const query = req.query;
    // 可扩展分页参数
    const list = await SysMenuService.list();
    R.success(res, buildTree(list));
  } catch (e: any) {
    R.error(res, e.message);
  }
}

export default withAuth(handler,{GET:'system:menu:list'}); 